var dataProxy = require('./util/getCDNData');
var _ = require('lodash');

module.exports = function*(next) {
	var req = this.request;
	var res = this.response;

	if (/success\.do$/.test(req.pathname)) {
		res.status(200)
			.type('json')
			.data(JSON.stringify({
				a: 1
			}));
		return;
	}

	// 测试接口
	if (/request\.do$/.test(req.pathname)) {
		var query = req.query,
			getProxyData = require('./util/getProxyData'),
			formatJs = require('./util/formatJS');

		var data =
			yield getProxyData.getData.bind(getProxyData, query.url);

		res.status(200)
			.type('json')
			.data(JSON.stringify({
				success: true,
				data: formatJs.format(JSON.stringify(data))
			}));
		return;
	}

	// 域名分页接口
	if (/domainPager\.do$/.test(req.pathname)) {
		var query = req.query,
			pageSize = query.pageSize,
			pageNumber = query.pageNumber;

		var resp =
			yield dataProxy.getCDNData.bind(dataProxy, 'describeUserDomains', {
				PageSize: pageSize,
				PageNumber: pageNumber
			});

		// 数据处理
		var dataHanlder = function(resp) {
			if (!resp) return;

			for (var i = 0, len = resp.Domains.PageData.length; i < len; i++) {
				var item = resp.Domains.PageData[i];

				switch (item.CdnType) {
					case 'web':
						item.CdnType = '图片小文件';
						break;
					case 'download':
						item.CdnType = '大文件下载';
						break;
					case 'video':
						item.CdnType = '视频流媒体';
						break;
					default:
						item.CdnType = '图片小文件';
						break;
				}
			}

			return resp;
		};

		// 执行数据处理函数
		dataHanlder(resp);

		res.status(200)
			.type('json')
			.data(JSON.stringify(resp));

		return;
	}

	// 添加加速域名
	if (/addCdnDomain\.do$/.test(req.pathname)) {
		var query = req.query;

		var resp =
			yield dataProxy.getCDNData.bind(dataProxy, 'addCdnDomain', {
				DomainName: query.domainName,
				SslFlag: query.sslFlag,
				CdnType: query.cdnType,
				SourceType: query.sourceType,
				Sources: query.sources
			});

		res.status(200)
			.type('json')
			.data(JSON.stringify(resp));

		return;
	}

	// 刷新文件内容
	if (/refreshObjectCaches\.do$/.test(req.pathname)) {
		var query = req.query;

		var resp =
			yield dataProxy.getCDNData.bind(dataProxy, 'refreshObjectCaches', {
				ObjectPath: query.objectPath,
				ObjectType: query.objectType
			});

		res.status(200)
			.type('json')
			.data(JSON.stringify(resp));

		return;
	}
	
	// 提交预热接口
	if (/pushCache\.do$/.test(req.pathname)) {
		var query = req.query;
		
		var resp = yield dataProxy.getCDNData.bind(dataProxy, 'pushObjectCache', { ObjectPath: query.path});
		
		res.status(200)
			.type('json')
			.data(JSON.stringify(resp));
		
		return;
	}
	
	// 资源监控接口
	if (/monitorData\.do$/.test(req.pathname)) {
		var query = req.query;
		var resp = yield dataProxy.getCDNData.bind(dataProxy, 'describeCdnMonitorData', { DomainName: query.domainName, StartTime: query.startTime || '', EndTime: query.endTime || ''});
		
		var averageSize = [], bytesHitRate = [], bytesPerSecond = [], queryPerSecond = [], requestHitRate = [];
		_.forEach(resp.MonitorDatas.CDNMonitorData,function(item){
			averageSize.push([+new Date(item.TimeStamp),+item.AverageObjectSize]);
			bytesHitRate.push([+new Date(item.TimeStamp),+item.BytesHitRate]);
			bytesPerSecond.push([+new Date(item.TimeStamp),+item.BytesPerSecond]);
			queryPerSecond.push([+new Date(item.TimeStamp),+item.QueryPerSecond]);
			requestHitRate.push([+new Date(item.TimeStamp),+item.RequestHitRate]);
		});
		
		var sortRule = function(a,b){
			return a[0] > b[0]
		}
		
		var data = {
			averageSize: averageSize.sort(sortRule), // 平均响应时间
			bytesHitRate: bytesHitRate.sort(sortRule), // 字节命中率
			bytesPerSecond: bytesPerSecond.sort(sortRule), // 流量
			queryPerSecond: queryPerSecond.sort(sortRule), // QPS
			requestHitRate: requestHitRate.sort(sortRule) // 请求命中率
		};
		
		res.status(200)
			.type('json')
			.data(JSON.stringify(data));
		
		return;
	}
	// 刷新文件内容，只能查询到7天内的数据
	if (/describeRefreshTasks\.do$/.test(req.pathname)) {
		var query = req.query,
			params = { PageSize: 1, PageNumber: 200 };
			
		if (query.taskId) {
			params.TaskId = query.taskId;
		}
		
		if (query.objectType) {
			params.ObjectPath = query.objectType;
		}

		var resp =
			yield dataProxy.getCDNData.bind(dataProxy, 'describeRefreshTasks', params);
		
		res.status(200)
			.type('json')
			.data(JSON.stringify(resp));

		return;
	}

	yield next;
}